package com.mijie.core;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Status {

	private HttpServletRequest request;
	private HttpServletResponse response;
	private int code;
	private String message;
	private Object result;
	private Map<String,Object> attr = null;
	
	public Status(){
		this(null,null);
	}
	
	public Status(HttpServletResponse response){
		this(null,response);
	}
	
	public Status(HttpServletRequest request,HttpServletResponse response){
		this.code = CoreStatusCode.PROC_SUCCESS;
		this.request = request;
		this.response = response;
	}
	
	public void setCode(int code){
		this.code = code;
	}
	
	public void setMessage(String message) {
		this.message = message;
	}


	public void setResult(Object result) {
		this.result = result;
	}
	
	public void addAttr(String key,Object value){
		if(attr==null) attr = new HashMap<String,Object>();
		attr.put(key, value);
	}

	
	public String toString(){
		StringBuilder sb = new StringBuilder();
		sb.append("{\"code\":").append(code);
		sb.append(",\"message\":\"").append(message==null?"":message).append("\"");
		if(attr!=null){
			for(String key : attr.keySet()){
				sb.append(",\""+key+"\":\"").append(attr.get(key)==null?"":attr.get(key)).append("\"");
			}
		}
		if(result!=null) sb.append(",\"result\":").append(result.toString());
		sb.append("}");
		return sb.toString();
	}
	
	public void write() {
		if(response==null) return;
		
		Writer writer = null;
		BufferedWriter out = null;
		Object value = null;
		try{
			writer = response.getWriter();
			out = new BufferedWriter(writer);
			out.write(toString());
		}catch(IOException e){
			
		}finally{
			try {
				if(out!=null) out.close();
				if(writer!=null) writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
